package com.ajaxdemo.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbDao {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	private static Connection conn;
	private static Statement stmt;
	private static ResultSet rs;

	/**
	 * 通过配置文件拿到必要属性
	 */
	static {
		Properties p = new Properties();
		try {
			p.load(DbDao.class.getClassLoader().getResourceAsStream(
					"DB.properties"));
			driver = p.getProperty("driver");
			url = p.getProperty("url");
			username = p.getProperty("username");
			password = p.getProperty("password");

			Class.forName(driver);
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拿到数据库连接
	 * 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static void getConn() throws ClassNotFoundException, SQLException {
		conn = DriverManager.getConnection(url, username, password);
	}

	/**
	 * 执行查询
	 * 
	 * @param sql
	 * @return ResultSet
	 */
	public static ResultSet queryDb(String sql) {
		try {
			getConn();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}

	/**
	 * 执行增删改
	 * 
	 * @param sql
	 * @return int
	 */
	public static int updateDb(String sql) {
		int rst = -1;
		try {
			getConn();
			stmt = conn.createStatement();
			rst = stmt.executeUpdate(sql);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		close();
		return rst;
	}

	/**
	 * 关闭连接
	 */
	public static void close() {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
